package com.walleipt.corgi.api.controller;

import java.util.Date;
import java.util.Map;

import org.mangoframework.core.annotation.Get;
import org.mangoframework.core.annotation.Post;
import org.mangoframework.core.annotation.RequestMapping;
import org.mangoframework.core.annotation.RequestParam;
import org.mangoframework.core.dispatcher.Parameter;

import com.walle.ak47.commons.utils.ConvertUtils;
import com.walleipt.corgi.api.annotations.Ignore;
import com.walleipt.corgi.api.common.dao.Page;
import com.walleipt.corgi.api.common.dao.mysql.SmartCommonDao;
import com.walleipt.corgi.api.data.bean.User;
import com.walleipt.corgi.api.ex.Message;
import com.walleipt.corgi.api.ex._HashMap;
import com.walleipt.corgi.api.service.ServiceFactory;
import com.walleipt.corgi.api.utils.AssertUtils;
import com.walleipt.corgi.api.utils.BeanUtils;
import com.walleipt.corgi.api.utils.MemoryUtils;
import com.walleipt.corgi.api.utils.StringUtils;

@RequestMapping("/userManager")
public class UserManagerController {

    /**
     * 修改
     * @param id
     * @param parameter
     * @return
     */
    @Post("{id}")
    public Object update(@RequestParam("id") String id, Parameter parameter) {
        User temp = MemoryUtils.getUser(parameter);
        AssertUtils.isTrue(id.equals(temp.getId()), "无操作权限");
        User user = BeanUtils.convert(User.class, parameter.getParamString());
        user.setPassword(null);
        user.setCreatetime(null);
        user.setId(id);
        user.setAvatar(null);
        int rs = ServiceFactory.instance().update(user);
        AssertUtils.isTrue(rs > 0, "操作失败");
        return rs;
    }

    @Ignore
    @Post("add")
    public Object add(Parameter parameter) {
        AssertUtils.notNull(parameter, "email", "password", "nickname");
        User user = BeanUtils.convert(User.class, parameter.getParamString());
        // 去空格
        /*user.setNickname(user.getNickname().trim());*/
        user.setEmail(user.getEmail().trim());
        AssertUtils.isTrue(StringUtils.isEmail(user.getEmail()), "请输入有效的邮箱");
        // 检查账号是否已存在
        AssertUtils.isTrue(!ServiceFactory.instance().checkEmailExists(user.getEmail()), Message.EMAIL_EXISTS);
        user.setPassword(StringUtils.password(user.getPassword()));
        user.setType(User.Type.USER);
        user.setCreatetime(new Date());
        user.setId(StringUtils.id());
        user.setStatus(User.Status.PENDING);
        int rs = ServiceFactory.instance().create(user);
        AssertUtils.isTrue(rs > 0, Message.OPER_ERR);
        String token = MemoryUtils.token();
        user.setPassword(null);
        MemoryUtils.putUser(token, user);
        return new _HashMap<>().add("token", token).add("user", user);
    }
    
    @Post("change")
    public Object change(Parameter parameter) {
        AssertUtils.notNull(parameter, "email", "nickname", "id");
        
        Map<String, Object> attrs = SmartCommonDao.instance().findById("user", parameter.getParamString().get("id")) ;
        attrs.put("id", parameter.getParamString().get("id")) ;
        attrs.put("email", parameter.getParamString().get("email")) ;
        attrs.put("nickname", parameter.getParamString().get("nickname")) ;
        try {
			SmartCommonDao.instance().update("user", attrs) ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return new _HashMap<>().add("user", attrs) ;
    }
    
    @Get("/del/{id}")
    public Object delUserById2(@RequestParam("id") String id,Parameter parameter)
    {
    	 SmartCommonDao dao = new SmartCommonDao() ;
    	 int size = dao.deleteById( "user", id ) ;
    	 return new _HashMap<>().add("changeSize", size);
    }
    
    @Get("/del/{id}")
    public Object delUserById(@RequestParam("id") String id,Parameter parameter)
    {
    	 SmartCommonDao dao = new SmartCommonDao() ;
    	 int size = dao.deleteById( "user", id ) ;
    	 return new _HashMap<>().add("changeSize", size);
    }
    
    @Post("/batchDel")
    public Object batchDelUser(Parameter parameter)
    {
    	String ids = parameter.getParamString().get( "ids" ) ;
    	int changeSize = SmartCommonDao.instance().batchDeleteByIds( "user", com.walle.ak47.commons.utils.StringUtils.toListStr( ids, ",") ) ;
    	return new _HashMap<>().add( "changeSize", changeSize );
    }
    
    @Get("allUsers")
    public Object getAllUsers(Parameter parameter) {
        String token = parameter.getParamString().get("token");
        MemoryUtils.getUser(token);
        
        SmartCommonDao dao = new SmartCommonDao() ;
        Page page = null;
		try {
			page = dao.paginateForMysql( ConvertUtils.toInt(parameter.getParamString().get("pageNum")),  ConvertUtils.toInt(parameter.getParamString().get("pageSize")), 
					"select * from user order by createTime desc", null );
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        return new _HashMap<>().add("page", page);
    }

}
